<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公寓名" prop="apartmentName">
        <el-input
          v-model="queryParams.apartmentName"
          placeholder="请输入公寓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-cascader
        ref="queryCascader"
        v-model="queryParams.addressArray"
        :options="regionOptions"
        :props="{
    checkStrictly: true,
    value: 'id',
    label: 'name',
    children: 'children',
    lazy: true,
    lazyLoad: this.lazyLoadCities
  }"
        clearable
        @change="handleAddressChange"
        placeholder="请选择省市"
      ></el-cascader>
      <el-form-item label="状态" prop="apartmentState">
        <el-select v-model="queryParams.apartmentState" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.apartment_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker clearable
          v-model="queryParams.createdAt"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['apartment:apartment:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['apartment:apartment:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['apartment:apartment:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['apartment:apartment:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="apartmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="公寓id" align="center" prop="apartmentId" />-->
      <el-table-column label="公寓名" align="center" prop="apartmentName" />
      <el-table-column label="图片信息" align="center" prop="apartmentImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.apartmentImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="apartmentState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.apartment_state" :value="scope.row.apartmentState"/>
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center" prop="detailedAddress" />
      <el-table-column label="朝向" align="center" prop="apartmentFace">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.apartment_face" :value="scope.row.apartmentFace"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="空房间数" align="center" prop="emptyRoomNum" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['apartment:apartment:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['apartment:apartment:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改公寓管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="公寓名" prop="apartmentName">
          <el-input v-model="form.apartmentName" placeholder="请输入公寓名" />
        </el-form-item>
        <el-form-item label="图片信息" prop="apartmentImage">
          <image-upload v-model="form.apartmentImage"/>
        </el-form-item>
        <!-- 修改添加或修改公寓管理对话框中的省市县输入框 -->
        <el-form-item label="省市" prop="addressArray">
        <el-cascader
          ref="formCascader"
          v-model="form.addressArray"
          :options="regionOptions"
          :props="{
    checkStrictly: true,
    value: 'id',
    label: 'name',
    children: 'children',
    lazy: true,
    lazyLoad: this.lazyLoadCities
  }"
          clearable
          @change="handleAddressChange"
          placeholder="请选择省市"
        ></el-cascader>
        </el-form-item>
        <el-form-item label="状态" prop="apartmentState">
          <el-select v-model="form.apartmentState" placeholder="请选择状态">
            <el-option
              v-for="dict in dict.type.apartment_state"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input v-model="form.detailedAddress" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="配套设施" prop="amenities">
          <el-checkbox-group v-model="form.amenities">
            <el-checkbox
              v-for="dict in dict.type.apartment_a"
              :key="dict.value"
              :label="dict.value">
              {{dict.label}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="朝向" prop="apartmentFace">
          <el-select v-model="form.apartmentFace" placeholder="请选择朝向">
            <el-option
              v-for="dict in dict.type.apartment_face"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="占地面积" prop="apartmentArea">
          <el-input
            v-model.number="form.apartmentArea"
            placeholder="请输入占地面积"
            @input="validateApartmentArea"
          >
            <template slot="append">平方米</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listApartment, getApartment, delApartment, addApartment, updateApartment, listProvinces, listCities } from "@/api/apartment/apartment";

export default {
  name: "Apartment",
  dicts: ['apartment_face', 'apartment_a', 'apartment_state'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公寓管理表格数据
      apartmentList: [],
      regionOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        apartmentName: null,
        apartmentAddress: null,
        apartmentState: null,
        createdAt: null,
        addressArray: [],
      },
      // 表单参数
      form: {
        addressArray: [],
      },
      // 表单校验
      rules: {
        apartmentName: [
          { required: true, message: "公寓名不能为空", trigger: "blur" }
        ],
        apartmentImage: [
          { required: true, message: "图片信息不能为空", trigger: "blur" }
        ],
        apartmentState: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        detailedAddress: [
          { required: true, message: "详细地址不能为空", trigger: "blur" }
        ],
        amenities: [
          { required: true, message: "配套设施不能为空", trigger: "blur" }
        ],
        apartmentFace: [
          { required: true, message: "朝向不能为空", trigger: "change" }
        ],
        apartmentArea: [
          { required: true, message: "占地面积不能为空", trigger: "blur" },
          { validator: this.validateApartmentArea, trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getRegionOptions();
  },
  methods: {
    validateApartmentArea(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入占地面积'));
      } else {
        const reg = /^\d+(\.\d{1,2})?$/;
        if (!reg.test(value)) {
          callback(new Error('请输入正确的数据 （正整数）'));
        } else {
          callback();
        }
      }
    },
    // 处理输入，格式化为两位小数
    handleApartmentAreaInput(value) {
      if (value === '') {
        this.form.apartmentArea = '';
      } else {
        this.form.apartmentArea = parseFloat(value).toFixed(2);
      }
    },

    // 获取省市选项
    getRegionOptions() {
      listProvinces().then(response => {
        this.regionOptions = response.data.map(province => ({
          id: province.id,
          name: province.name,
          leaf: false
        }));
      });
    },

    // 懒加载城市选项
    lazyLoadCities(node, resolve) {
      if (node.level === 0) {
        resolve(this.regionOptions);
      } else if (node.level === 1) {
        listCities(node.data.id).then(response => {
          const cities = response.data.map(city => ({
            id: city.id,
            name: city.name,
            leaf: true
          }));
          resolve(cities);
        });
      } else {
        resolve([]);
      }
    },

    // 处理查询表单的地址变化
    handleAddressChange(value) {
      if (value && value.length > 0) {
        const labels = this.$refs.queryCascader.getCheckedNodes()[0].pathLabels;
        this.queryParams.apartmentAddress = labels.join(' ');
      } else {
        this.queryParams.apartmentAddress = '';
      }
    },

    handleFormAddressChange(value) {
      if (value && value.length > 0) {
        const labels = this.$refs.formCascader.getCheckedNodes()[0].pathLabels;
        this.form.apartmentAddress = labels.join(' ');
      } else {
        this.form.apartmentAddress = '';
      }
    },
    /** 查询公寓管理列表 */
    getList() {
      this.loading = true;
      listApartment(this.queryParams).then(response => {
        this.apartmentList = response.rows.map(row => ({
          ...row,
          addressArray: row.apartmentAddress ? row.apartmentAddress.split(' ') : []
        }));
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        apartmentId: null,
        apartmentName: null,
        apartmentImage: null,
        apartmentAddress: null,
        apartmentState: null,
        detailedAddress: null,
        isDeleted: null,
        amenities: [],
        apartmentFace: null,
        createdAt: null,
        apartmentArea: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.apartmentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加公寓管理";
      this.form.addressArray = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const apartmentId = row.apartmentId || this.ids
      getApartment(apartmentId).then(response => {
        this.form = response.data;
        this.form.amenities = this.form.amenities ? this.form.amenities.split(",") : [];
        this.form.addressArray = this.form.apartmentAddress ? this.form.apartmentAddress.split(' ').map(name => {
          const province = this.regionOptions.find(p => p.name === name);
          return province ? province.id : name;
        }) : [];
        this.open = true;
        this.title = "修改公寓管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.addressArray && this.form.addressArray.length > 0) {
            const labels = this.$refs.formCascader.getCheckedNodes()[0].pathLabels;
            this.form.apartmentAddress = labels.join(' ');
          } else {
            this.form.apartmentAddress = '';
          }

          this.form.amenities = this.form.amenities.join(",");

          if (this.form.apartmentId != null) {
            updateApartment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addApartment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
          if (this.form.apartmentArea !== null && this.form.apartmentArea !== '') {
            this.form.apartmentArea = parseFloat(this.form.apartmentArea).toFixed(2);
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const apartmentIds = row.apartmentId || this.ids;
      this.$modal.confirm('是否确认删除公寓管理编号为"' + apartmentIds + '"的数据项？').then(function() {
        return delApartment(apartmentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('apartment/apartment/export', {
        ...this.queryParams
      }, `apartment_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
